<?php

namespace addons\AppVersions\merchant\controllers;

use Yii;
use yii\web\Response;
use common\enums\StatusEnum;
use common\models\base\SearchModel;
use common\helpers\ArrayHelper;
use common\traits\MerchantCurd;
use addons\AppVersions\common\enums\TypeEnum;
use addons\AppVersions\common\models\AppVersions;
use addons\AppVersions\common\models\SettingForm;
use addons\AppVersions\common\models\Cate;

/**
 * Class VersionsController
 * @package addons\AppVersions\backend\controllers
 * @author YiiFrame <21931118@qq.com>
 */
class VersionsController extends BaseController
{
    use MerchantCurd;

    /**
     * @var AppVersions
     */
    public $modelClass = AppVersions::class;

    /**
     * 首页
     *
     * @return string
     * @throws \yii\web\NotFoundHttpException
     */
    public function actionIndex()
    {
        $type = Yii::$app->request->get('type', TypeEnum::ANDROID);

        $searchModel = new SearchModel([
            'model' => $this->modelClass,
            'scenario' => 'default',
            'partialMatchAttributes' => ['title', 'version'], // 模糊查询
            'defaultOrder' => [
                'version_id' => SORT_DESC,
            ],
            'pageSize' => $this->pageSize,
        ]);

        $dataProvider = $searchModel
            ->search(Yii::$app->request->queryParams);
        $dataProvider->query
            ->andWhere(['>=', 'status', StatusEnum::DISABLED])
            ->andWhere(['type' => $type])
            ->andWhere(['merchant_id' => Yii::$app->services->merchant->getNotNullId()]);

        $setting = new SettingForm();
        $setting->attributes = $this->getConfig();

        return $this->render($this->action->id, [
            'dataProvider' => $dataProvider,
            'searchModel' => $searchModel,
            'setting' => $setting,
            'cateMap' => $this->getCateMap(),
            'type' => $type,
        ]);
    }

    /**
     * 编辑/创建
     *
     * @return mixed
     */
    public function actionEdit()
    {
        $id = Yii::$app->request->get('id', null);
        $model = $this->findModel($id);
        $model->type = Yii::$app->request->get('type', TypeEnum::ANDROID);

        // iOS 设置链接
        if (
            $model->type == TypeEnum::IOS &&
            ($version = AppVersions::find()
                ->where([
                    'type' => TypeEnum::IOS,
                    'status' => StatusEnum::ENABLED,
                    'merchant_id' => $this->getMerchantId()
                ])
                ->orderBy('version_id desc')
                ->one()
            )
        ) {
            $model->download_url = $version->download_url;
        }

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['index', 'type' => $model->type]);
        }

        return $this->render($this->action->id, [
            'model' => $model,
            'cateMap' => $this->getCateMap(),
        ]);
    }

    /**
     * 二维码转换
     *
     * @return mixed
     * @throws \yii\base\InvalidConfigException
     */
    public function actionQr()
    {
        $getUrl = Yii::$app->request->get('url');

        $qr = Yii::$app->get('qr');
        Yii::$app->response->format = Response::FORMAT_RAW;
        Yii::$app->response->headers->add('Content-Type', $qr->getContentType());

        return $qr->setText($getUrl)
            ->setSize(300)
            ->setMargin(7)
            ->writeString();
    }

    /**
     * @return array
     */
    public function getCateMap()
    {
        return ArrayHelper::map(
            Cate::find()
                ->where([
                    'status' => StatusEnum::ENABLED,
                    'merchant_id' => Yii::$app->services->merchant->getNotNullId()
                ])
                ->all(),
            'name',
            'title'
        );
    }
}